package com.atguigu.network;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author yihu
 * @create 2021-06-15 15:35
 * @email:1057202547@qq.com
 * @dec:UDPd协议的网络编程
 */
public class UDPTest {

    //发送端
    @Test
    public void sender()  {
        DatagramSocket socket = null;
        try {
            //1 创建soket
            socket = new DatagramSocket();

            //2 封装一个DatagramPacket数据报
            String str = "我是UDP方式发送的导弹";
            byte[] data = str.getBytes();
            InetAddress inet = InetAddress.getLocalHost();
            DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

            //3.发送
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null){
                socket.close();
            }
        }
    }

    //接收端
    @Test
    public void receiver() throws IOException {
        //1 创建soket
        DatagramSocket socket = new DatagramSocket(9090);

        //2接收数据
        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

        socket.receive(packet);

        System.out.println(new String(packet.getData(),packet.getLength()));

        socket.close();

    }

}
